package com.ihunanren.weixin.module.screen;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.google.common.base.Throwables;
import com.ihunanren.biz.result.Result;
import com.ihunanren.biz.weixin.WeixinXmlParser;
import com.ihunanren.biz.weixin.ao.IWeixinAO;
import com.ihunanren.biz.weixin.domain.WeixinMsg;
import com.ihunanren.common.Pair;
import com.ihunanren.dao.WeixinMsgType;

/**
 * @author kalman03
 */
public class WeixinCallback {

	@Autowired
	private IWeixinAO weixinAO;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	private final static Logger log = LoggerFactory.getLogger(WeixinCallback.class);

	public void execute(
			@Param(name = "nonce", defaultValue = "") String nonce,
			@Param(name = "timestamp", defaultValue = "") String timestamp,
			@Param(name = "signature", defaultValue = "") String weixinSignature,
			@Param(name = "id", defaultValue = "") String id, Context context) {
		
		if (weixinAO.isWeixinAuthRequest(nonce, timestamp, weixinSignature, id)) {
			if ("GET".equalsIgnoreCase(request.getMethod())) {
				doGet(context);
			} else {
				doPost(context);
			}
		}
	}

	
	
	/** 执行GET请求 */
	private void doGet(Context context) {
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");
		String weixinSignature = request.getParameter("signature");
		String id = request.getParameter("id");
		if (weixinAO.isWeixinAuthRequest(nonce, timestamp, weixinSignature, id)) {
			try {
				PrintWriter out = response.getWriter();
				out.print( request.getParameter("echostr"));
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//context.put("result", request.getParameter("echostr"));
		}
	}

	/** 执行POST请求 */
	private void doPost(Context context) {
		try {
			InputStream inputStream = getStandardXmlInputStream();
			String id = request.getParameter("id");

			Pair<? extends WeixinMsg, WeixinMsgType> pair = WeixinXmlParser.toWeixinMsg(inputStream);

			//weixinAO.saveWeixinReplyMsg(pair, Long.parseLong(id));
			
			Result result = weixinAO.getReplyMsgResponse(pair, Long.parseLong(id));
			
			response.setContentType("text/xml");
			
			if(result.isSuccess()){
				PrintWriter out = response.getWriter();
				out.print( result.getDefaultModel());
				out.flush();
				out.close();
			}else{
				log.error(request.getReader().toString());
			}
			
		} catch (Exception e) {
			System.out.println(e);
			Throwables.propagate(e);
		}
	}

	/**
	 * 微信返回的不是标准的xml，tmd扯蛋了
	 * @return
	 * @throws IOException
	 */
	private InputStream getStandardXmlInputStream() throws IOException {
		//InputStream inputStream = request.getInputStream();
		BufferedReader in = request.getReader();
		StringBuilder buffer = new StringBuilder();
		buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		String line = "";
		while ((line = in.readLine()) != null) {
			buffer.append(line);
		}
		return new ByteArrayInputStream(buffer.toString().getBytes());
	}
}
